package com.ghsc.ghxc.jsb.ui
import android.Manifest
import android.content.Intent
import android.text.TextUtils
import com.cn.appcore.base.BaseVMActivity
import com.cn.appcore.ext.getCompatColor
import com.cn.appcore.ext.loge
import com.cn.appcore.ext.showToast
import com.cn.appcore.ext.startKtxActivityKill
import com.cn.appcore.http.constant.HttpConstant
import com.cn.appcore.utils.ApkUtil
import com.cn.appcore.utils.GlideUtil
import com.cn.appcore.utils.GsonUtil
import com.cn.appcore.utils.Preference
import com.ghsc.ghxc.jsb.R
import com.ghsc.ghxc.jsb.app.App
import com.ghsc.ghxc.jsb.config.CustKey
import com.ghsc.ghxc.jsb.config.UserManager
import com.ghsc.ghxc.jsb.databinding.ActivityLaunchBinding
import com.ghsc.ghxc.jsb.ui.bean.SysConfigResult
import com.ghsc.ghxc.jsb.ui.bean.VersionDataBean
import com.ghsc.ghxc.jsb.ui.login.LoginActivity
import com.ghsc.ghxc.jsb.ui.main.MainActivity
import com.ghsc.ghxc.jsb.view.VersionPopView
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.enums.PopupAnimation
import com.permissionx.guolindev.PermissionX
import com.zj.zjsdk.ad.ZjAdError
import com.zj.zjsdk.ad.ZjSplashAd
import com.zj.zjsdk.ad.ZjSplashAdListener
import com.zj.zjsdk.api.v2.splash.ZJSplashAd
import com.zj.zjsdk.api.v2.splash.ZJSplashAdInteractionListener
import com.zj.zjsdk.api.v2.splash.ZJSplashAdLoadListener

/**
 * 项目：GuoHuaMall
 * 包名：com.whale.foreignexchange.ui
 * 类名：LaunchActivity
 * 创建时间：2023/4/6 20:59
 * 创建人 @author： xiaolin
 * 描述 ：Todo...
 */
class LaunchActivity : BaseVMActivity<LaunchViewModel, ActivityLaunchBinding>()  {
    override fun attachLayoutRes(): Int {
        return R.layout.activity_launch
    }


    override fun onStart() {
        super.onStart()
        if (!isTaskRoot) {
            val intent = intent
            val intentAction = intent.action;
            if (intent.hasCategory(Intent.CATEGORY_LAUNCHER) && intentAction != null && intentAction.equals(
                    Intent.ACTION_MAIN
                )
            ) {
                finish()
                return
            }
        }
    }


    private var isClick = false //是否进行了点击
    private var isPause = false // 广告被点击后，当前activity是否pause
    private var isOnPause = false //判断是否跳转了广告落地页
    var isShow = false //因为首次安装打开。会走2次
    override fun initView() {
//        lifecycleScope.launch{
//            delay(1000)
//            openActivity()
//        }

        mViewModel.onSysConfigMethod("")

    }

    fun cheAdvData(){
//        lifecycleScope.launch{
//            openActivity()
//        }
        loadZjAdv(CustKey.zjKaiPing)
    }


    private fun openActivity() {
        var isLogin: String by Preference(HttpConstant.APP_IS_LOGIN, "")
        if (isLogin=="1"){
            startKtxActivityKill<MainActivity>()
        }else {
            startKtxActivityKill<LoginActivity>()
        }

    }

    override fun attachVMClass(): Class<LaunchViewModel>? {
        return LaunchViewModel::class.java
    }


    override fun initRequestObserver() {
        super.initRequestObserver()
        mViewModel.apply {
            errorMsg.observe(this@LaunchActivity) {
                showToast(it)
            }
            againLoginMsg.observe(this@LaunchActivity) {
                showToast(CustKey.IN_AGAIN_MSG)

            }
            onSysConfigData.observe(this@LaunchActivity) {
                var imgStr=it.getStrImg()
                isShow=true  //因为首次安装打开。会走2次
                loge("我草==启动也==="+imgStr)
                if (!TextUtils.isEmpty(imgStr)) {
                    GlideUtil.ImageLoad(this@LaunchActivity,imgStr,binding.imgBg)
                }
                //保存配置
                UserManager.saveConfig(it)
                if (UserManager.getIsFirst()!="1"){
                    UserManager.setIsFirst("1")
                    App.init()
                } else  UserManager.setIsFirst("1")
                appVersionUpData(it)

//                for (i in it.list.indices)
//                    loge("xxxx==="+it.list[i].cfg_key+"vvvv="+it.list[i].cfg_value)



            }
        }
    }

    /** 版本更新 **/
    fun  appVersionUpData (bean : SysConfigResult){
        bean.let {
            //版本更新
            var sysConfigResultData = it.getSysConfigBean( CustKey.configK5 )
            if(sysConfigResultData!=null)
            if(!TextUtils.isEmpty(sysConfigResultData.cfg_value)){
                val bean =GsonUtil.GsonToJsonClass(sysConfigResultData.cfg_value, VersionDataBean::class.java)
                val versionName  = ApkUtil.getVersionName()
                //和最小的版本对比  小于后台的最小，强制更新
                val versionSign = ApkUtil.compareVersion(versionName, bean.version)
                if(versionSign<0){
                    if (bean.url.contains(".apk")){
                        loge("当前版本-"+bean.url)
                        isPermissionX(bean)
                    }else{
                        cheAdvData()
                        //更新链接措辞
//                        val map: HashMap<String, Any> = HashMap()
//                        map["url"] = bean.url
//                        GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onGetUrlApkMethod( it1) }
                    }
                }else{
                    //
                    cheAdvData()
                }
            }
        }
    }
    private  fun isPermissionX(bean : VersionDataBean){
        //和最小的版本对比  小于后台的最小，强制更新
        if (!TextUtils.isEmpty(bean.version) || !TextUtils.isEmpty(bean.url) ){
            PermissionX.init(this@LaunchActivity)
                .permissions(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .request { allGranted, _, _ ->
                    if (allGranted) {
                        upApk(bean)
                    } else {
                        showToast("需开启权限才能进行操作")
                    }
                }
        }
    }
    private fun upApk( versionDataBean:VersionDataBean){
        XPopup.Builder(this@LaunchActivity)
            .popupAnimation(PopupAnimation.ScaleAlphaFromCenter)
            .customHostLifecycle(lifecycle)
            .dismissOnTouchOutside(false)
            .hasShadowBg(true)
            .enableDrag(false)
            .navigationBarColor(getCompatColor(R.color.bg_dark_color))
            //这个属性必须加，不然GiftFragment出问题
            .isViewMode(true)
            .asCustom(VersionPopView(this@LaunchActivity, versionDataBean).apply {
                setOnCloseDismiss {
                    //广告进入
                    cheAdvData()
                }
            })
            .show()
    }
    // 广告是否被点击
    private var isAdClicked = false
    /** 众间 广告 **/
    private fun loadZjAdv(keyId:String){
        loge("开屏-----zhongjian的广告的广告")


        ZJSplashAd.loadAd(this,keyId, object : ZJSplashAdInteractionListener,
            ZJSplashAdLoadListener {
            override fun onSplashAdShow() {

            }

            override fun onSplashAdClick() {
                isAdClicked = true
            }

            override fun onSplashAdShowError(p0: Int, p1: String) {
                openActivity()
            }

            override fun onSplashAdClose() {
                if (!isPause) {
                    openActivity()
                }
            }

            override fun onError(p0: Int, p1: String) {
                openActivity()
            }

            override fun onAdLoaded(p0: ZJSplashAd) {
                p0.setAdInteractionListener(this)
                p0.show(binding.adFragment)
            }
        }
        )
    }

    override fun onPause() {
        super.onPause()
        if (isClick) {
            isOnPause = true
        }
        if (isAdClicked) {
            isPause = true
        }
    }

    override fun onResume() {
        super.onResume()
        if (isOnPause) { //判断是否点击，并且跳转了落地页，如果是，就相当于走了onclose
            openActivity()
        }
        if (isPause) openActivity()
    }
}